# coding: utf-8
from PySide6.QtCore import Qt
from PySide6.QtGui import QColor, QTextTableFormat
from PySide6.QtWidgets import QApplication, QVBoxLayout, QFrame
from qfluentwidgets import TransparentToolButton, FluentIcon as FIF, FlowLayout, HorizontalSeparator, ToolTipFilter, \
    ToolTipPosition, MessageBox, MessageBoxBase, SubtitleLabel, BodyLabel, CaptionLabel

from .line_edit import ElTextEdit, ElLineEdit
from ...common import ElStyleSheet, ElIcon


class RichButton(TransparentToolButton):
    def _postInit(self):
        self.setFixedSize(30, 30)
        self.installEventFilter(ToolTipFilter(self, position=ToolTipPosition.BOTTOM))


class InsertTableDialog(MessageBoxBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.titleLabel = SubtitleLabel('插入表格', self)
        self.rowCountEdit = ElLineEdit(self)
        self.columnCountEdit = ElLineEdit(self)
        self.rowWarningLabel = self.createWarningLabel("行数不能为空")
        self.columnWarningLabel = self.createWarningLabel("列数不能为空")

        self.rowCountEdit.setPlaceholderText("请输入行数")
        self.columnCountEdit.setPlaceholderText("请输入列数")

        self.viewLayout.addWidget(self.titleLabel)
        self.viewLayout.addWidget(BodyLabel("行数：", self))
        self.viewLayout.addWidget(self.rowCountEdit)
        self.viewLayout.addWidget(self.rowWarningLabel)
        self.viewLayout.addWidget(BodyLabel("列数：", self))
        self.viewLayout.addWidget(self.columnCountEdit)
        self.viewLayout.addWidget(self.columnWarningLabel)

        self.yesButton.setText("插入")
        self.cancelButton.setText("取消")
        self.widget.setMinimumWidth(500)

    def createWarningLabel(self, text: str):
        label = CaptionLabel(text, self)
        label.setTextColor("#cf1010", QColor(255, 28, 32))
        label.hide()
        return label

    def validate(self):
        row = self.rowCountEdit.text()
        column = self.columnCountEdit.text()
        if not row.isdigit() or not column.isdigit():
            self.rowWarningLabel.setText("请输入数字")
            self.columnWarningLabel.setText("请输入数字")
            self.rowWarningLabel.show()
            self.columnWarningLabel.show()
            return False
        row = int(row)
        column = int(column)
        if row <= 0 or column <= 0:
            self.rowWarningLabel.show()
            self.columnWarningLabel.show()
            return False
        self.rowWarningLabel.hide()
        self.columnWarningLabel.hide()
        return True


class RichTextEdit(QFrame):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.verticalLayout = QVBoxLayout(self)
        self.flowLayout = FlowLayout()
        self.textEdit = ElTextEdit(self)
        # 按钮
        self.undoButton = RichButton(ElIcon.Undo, self)
        self.redoButton = RichButton(ElIcon.Redo, self)
        self.cutButton = RichButton(FIF.CUT, self)
        self.copyButton = RichButton(FIF.COPY, self)
        self.pasteButton = RichButton(FIF.PASTE, self)
        self.boldButton = RichButton(ElIcon.Bold, self)
        self.italicButton = RichButton(ElIcon.Italic, self)
        self.underlineButton = RichButton(ElIcon.Underline, self)
        self.fontSizeButton = RichButton(ElIcon.FontSize, self)
        self.alignLeftButton = RichButton(ElIcon.AlignLeft, self)
        self.alignCenterButton = RichButton(ElIcon.AlignCenter, self)
        self.alignRightButton = RichButton(ElIcon.AlignRight, self)
        self.alignJustifyButton = RichButton(ElIcon.AlignJustify, self)
        self.bulletListButton = RichButton(ElIcon.UnorderedList, self)
        self.numberedListButton = RichButton(ElIcon.OrderedList, self)
        self.insertLinkButton = RichButton(ElIcon.InsertLink, self)
        self.insertImageButton = RichButton(ElIcon.Image, self)
        self.insertTableButton = RichButton(ElIcon.Table, self)
        self.codeButton = RichButton(FIF.CODE, self)
        self.clearButton = RichButton(FIF.DELETE, self)

        self.__initWidgets()

    def __initWidgets(self):
        ElStyleSheet.RICH_TEXT_EDIT.apply(self.textEdit)
        ElStyleSheet.RICH_TEXT_EDIT.apply(self)
        self.textEdit.setAcceptRichText(True)

        self.undoButton.setToolTip("撤销")
        self.redoButton.setToolTip("重做")
        self.cutButton.setToolTip("剪切")
        self.copyButton.setToolTip("复制")
        self.pasteButton.setToolTip("粘贴")
        self.boldButton.setToolTip("加粗")
        self.italicButton.setToolTip("斜体")
        self.underlineButton.setToolTip("下划线")
        self.fontSizeButton.setToolTip("字体")
        self.alignLeftButton.setToolTip("左对齐")
        self.alignCenterButton.setToolTip("居中")
        self.alignRightButton.setToolTip("右对齐")
        self.alignJustifyButton.setToolTip("两端对齐")
        self.bulletListButton.setToolTip("插入无序列表")
        self.numberedListButton.setToolTip("插入有序列表")
        self.insertLinkButton.setToolTip("插入链接")
        self.insertImageButton.setToolTip("插入图片")
        self.insertTableButton.setToolTip("插入表格")
        self.clearButton.setToolTip("清空")

        self.__initLayout()
        self.__connectSignals()

    def __initLayout(self):
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.addLayout(self.flowLayout)
        self.verticalLayout.addWidget(HorizontalSeparator(self))
        self.verticalLayout.addWidget(self.textEdit)

        self.flowLayout.addWidget(self.undoButton)
        self.flowLayout.addWidget(self.redoButton)
        self.flowLayout.addWidget(self.cutButton)
        self.flowLayout.addWidget(self.copyButton)
        self.flowLayout.addWidget(self.pasteButton)
        self.flowLayout.addWidget(self.boldButton)
        self.flowLayout.addWidget(self.italicButton)
        self.flowLayout.addWidget(self.underlineButton)
        self.flowLayout.addWidget(self.fontSizeButton)
        self.flowLayout.addWidget(self.alignLeftButton)
        self.flowLayout.addWidget(self.alignCenterButton)
        self.flowLayout.addWidget(self.alignRightButton)
        self.flowLayout.addWidget(self.alignJustifyButton)
        self.flowLayout.addWidget(self.bulletListButton)
        self.flowLayout.addWidget(self.numberedListButton)
        self.flowLayout.addWidget(self.insertLinkButton)
        self.flowLayout.addWidget(self.insertImageButton)
        self.flowLayout.addWidget(self.insertTableButton)
        self.flowLayout.addWidget(self.codeButton)
        self.flowLayout.addWidget(self.clearButton)

    def __connectSignals(self):
        self.undoButton.clicked.connect(self.textEdit.undo)
        self.redoButton.clicked.connect(self.textEdit.redo)
        self.cutButton.clicked.connect(self.textEdit.cut)
        self.copyButton.clicked.connect(self.textEdit.copy)
        self.pasteButton.clicked.connect(self.textEdit.paste)
        self.boldButton.clicked.connect(self.bold)
        self.italicButton.clicked.connect(self.italic)
        self.underlineButton.clicked.connect(self.underline)
        self.alignLeftButton.clicked.connect(self.setTextAlign)
        self.codeButton.clicked.connect(self.showCodeDialog)
        self.insertTableButton.clicked.connect(self.insertTable)
        self.clearButton.clicked.connect(self.textEdit.clear)

    def setPlaceholderText(self, text: str):
        self.textEdit.setPlaceholderText(text)

    def bold(self):
        pass

    def italic(self):
        pass

    def underline(self):
        pass

    def setTextAlign(self, algn: Qt.AlignmentFlag):
        pass

    def insertTable(self):
        dialog = InsertTableDialog(self.window())
        if dialog.exec():
            cursor = self.textEdit.textCursor()
            row = int(dialog.rowCountEdit.text())
            column = int(dialog.columnCountEdit.text())
            table = cursor.insertTable(row, column)

    def showCodeDialog(self):
        html = self.textEdit.toHtml()
        dialog = MessageBox('Html代码', html, self.window())
        dialog.yesButton.setText("复制")
        dialog.cancelButton.setText("取消")
        if dialog.exec():
            QApplication.clipboard().setText(html)
